import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateAlarmDto, UpdateAlarmDto, QueryAlarmDto } from './dto/alarm.dto';
import { AlarmEntity } from './entities/alarm.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class AlarmService {
  constructor(
    @InjectRepository(AlarmEntity)
    private readonly alarmEntityRep: Repository<AlarmEntity>,
  ) {}

  async create(createAlarmDto: CreateAlarmDto) {
    const res = await this.alarmEntityRep.save(createAlarmDto);
    return ResultData.ok(res);
  }

  async findAll(query: QueryAlarmDto) {
    const entity = this.alarmEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.userId)) {
      entity.andWhere('entity.userId = :userId', { userId: query.userId });
    }
    if (!isEmpty(query.childId)) {
      entity.andWhere('entity.childId = :childId', { childId: query.childId });
    }
    if (!isEmpty(query.alarmType)) {
      entity.andWhere('entity.alarmType = :alarmType', { alarmType: query.alarmType });
    }
    if (!isEmpty(query.alarmTriggerContent)) {
      entity.andWhere('entity.alarmTriggerContent = :alarmTriggerContent', { alarmTriggerContent: query.alarmTriggerContent });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select(['entity.id', 'entity.userId', 'entity.childId', 'entity.alarmType', 'entity.alarmTriggerContent']);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.alarmEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateAlarmDto: UpdateAlarmDto) {
    const res = await this.alarmEntityRep.update({ id: updateAlarmDto.id }, updateAlarmDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(ids: number[]) {
    const res = await this.alarmEntityRep.update(
      { id: In(ids) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async deleteByUserId(id: number) {
    const res = await this.alarmEntityRep.update(
      { userId: id },
      {
        delFlag: '1',
      },
    );

    console.log('删除用户告警记录', JSON.stringify(res));
    return res.affected >= 1;
  }

  // 使用原生SQL进行多表联查
  async getMessageAlarmList(userId: number, pageNum: number = 1, pageSize: number = 10) {
    // 确保参数是数字类型
    const offset = Number(pageSize) * (Number(pageNum) - 1);
    const limit = Number(pageSize);
    const uid = Number(userId);

    const sql = `
      select ma.id,
             ma.user_id userId,
             ma.child_id childId,
             ma.alarm_type alarmType,
             ma.alarm_trigger_content alarmTriggerContent,
             ma.del_flag delFlag,
             ma.create_time createTime,
             ma.update_time updateTime,
             ci.child_nickname as childNickname,
             ci.avatar         as avatar
      from message_alarm ma
               right join child_info ci on ma.child_id = ci.user_id and ci.del_flag = '0'
      where ma.del_flag = '0'
        and ma.user_id = ?
      order by ma.create_time desc limit ? offset ?
  `;

    // 计算总数的SQL
    const countSql = `
      select count(*) as total
      from message_alarm ma
               right join child_info ci on ma.child_id = ci.user_id and ci.del_flag = '0'
      where ma.del_flag = '0'
        and ma.user_id = ?;
  `;

    // 执行原生SQL查询
    const [list, countResult] = await Promise.all([this.alarmEntityRep.query(sql, [uid, limit, offset]), this.alarmEntityRep.query(countSql, [uid])]);

    const total = countResult[0].total;

    return ResultData.ok({
      list,
      total,
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
    });
  }
}
